package com.appjishu.web.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.appjishu.passport.annotation.AuthController;
import com.appjishu.passport.intercepter.LoginInterceptor;
import com.appjishu.web.constant.Const;
import com.appjishu.web.model.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.val;
import org.apache.poi.ss.usermodel.Picture;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequestMapping("file")
@RestController
@AuthController
public class FileController {
    @Value("${file.url}")
    private String fileUploadUrl;

    @Value("${file.loc}")
    private String fileLocPath;

    @ApiOperation("8.0 附件_上传")
    @PostMapping(value = "/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> map = new HashMap<>();
        try {
            //文件上传
            String hostAddress = InetAddress.getLocalHost().getHostAddress();//获取文件的名称
            String filename = file.getOriginalFilename();
            //上传的文件夹
            Long userId = LoginInterceptor.getUserId();
            String date = DateTimeFormatter.ofPattern(Const.DATE_FORMAT).format(LocalDate.now());
            String filePath = fileLocPath + date + File.separator + userId + File.separator;
            java.io.File path = new java.io.File(filePath);
            if (!path.exists()) {
                path.mkdirs();
            }

            String uuid = IdUtil.simpleUUID();
            String fileStr = filename.substring(filename.lastIndexOf("."));
            String newFileName = uuid + fileStr;
            //上传的文件
            String rootFilePath = filePath + newFileName;
            //上传
            FileUtil.writeBytes(file.getBytes(), rootFilePath);//使用Hutool工具包将我们接收到文件保存到rootFilePath中
            map.put("filename", filename);
            map.put("path", fileUploadUrl + date + "/" + userId + "/" + newFileName);
            map.put("size", file.getSize());
            map.put("loadPath",rootFilePath);
        } catch (Exception e) {
           throw new IOException(e);
        }
        return Result.success(map);
    }

    @GetMapping("/{method}/{date}/{userId}/{flag}")
    @ApiOperation("8.1 附件_下载")
    public void getFiles(@PathVariable String method,@PathVariable String date,@PathVariable String userId,@PathVariable String flag, HttpServletResponse response, HttpServletRequest req) throws IOException {
        OutputStream os;//新建一个输出流对象
        String basePath = fileLocPath+ date + File.separator + userId + File.separator;
        List<String> fileNames = FileUtil.listFileNames(basePath);//获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                java.io.File file = new java.io.File(basePath + fileName);
                long length = file.length();
                if("download".equals(method)) {
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                    response.setContentType("application/octet-stream");
                } else if("preview".equals(method)) {
                    response.setContentType("image/png;charset=UTF-8");
                }
                response.addHeader("totalSize", String.valueOf(length));
                response.setContentLengthLong(length);
                byte[] bytes = FileUtil.readBytes(file);//通过文件的路径读取文件字节流
                os = response.getOutputStream();//通过response的输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            throw new IOException(e);
        }

    }
}
